package com.appbee.media.client.presenter;

import javax.inject.Inject;

import com.appbee.core.client.place.EditPlace;
import com.appbee.core.client.place.HasPlace;
import com.appbee.core.client.place.IndexPlace;
import com.appbee.media.shared.MediaProxy;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.RangeChangeEvent;

public class MediaThumbnailActivity extends AbstractMediaActivity
implements
		HasPlace
{
	public interface View extends IsWidget
	{
		void setActivity(MediaThumbnailActivity activity);

		HasData<MediaProxy> getHasData();
		
	}

	protected MediaDataProvider dataProvider;
	protected IndexPlace place;
	protected View view;
	private HandlerRegistration handlerRegistration;
	
	@Inject
	public MediaThumbnailActivity(View view,MediaDataProvider dataProvider)
	{
		this.view = view;
		this.dataProvider = dataProvider;
		view.setActivity(this);
	}
	
	@Override
	public void start(final AcceptsOneWidget panel, EventBus eventBus)
	{
		GWT.log("Start MediaThumbnail");
		dataProvider.addDataDisplay(view.getHasData());
		//Keep track of datarange in url history.
		handlerRegistration = this.view.getHasData().addRangeChangeHandler(new RangeChangeEvent.Handler()
		{
			
			@Override
			public void onRangeChange(RangeChangeEvent event)
			{
				GWT.log("RangeChangeEvent: "+event.getNewRange().getStart());
				place.setIndex(event.getNewRange().getStart());
				placeController.setPlaceStateChange(place);
			}
		});
		int start = Math.max(0,place.getIndex());
		view.getHasData().setVisibleRange(start, 9);
		panel.setWidget(view);
		
	}
	
	@Override
	public void onStop()
	{
		GWT.log("stop: Media");
		handlerRegistration.removeHandler();
		dataProvider.removeDataDisplay(view.getHasData());
		super.onStop();
	}

	@Override
	public void setPlace(Place place)
	{
		this.place = (IndexPlace) place;
	}

	public void mediaViewClick(MediaProxy mediaProxy, int index)
	{
		placeController.goTo(new EditPlace("media",mediaProxy.getId()));
	}

}
